package com.wuhan.template.views;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2016/5/16 0016.
 */
public class CheckVersionUtils {

    private Context context;
    private String versionUrl = "http://localhost:8080/student/version.txt";

    public CheckVersionUtils(Context context) {
        this.context = context;
    }

    private String getAppVersion() {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), 0);
            return  packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String getServerVersion(){
        try {
            URL url = new URL(versionUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.connect();
           /* con.setConnectTimeout(15000);
            con.setReadTimeout(30000);*/
            if(con.getResponseCode()==200){
                InputStream stream = con.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                return reader.readLine();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 2.0+"";
    }

    public boolean isNeedUpdate(){
        String appVersion = getAppVersion();
        String serverVersion = getServerVersion();
        if(serverVersion.compareTo(appVersion)>0){
            return true;
        }
        return false;
    }

}
